﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;
using MS.InformationManagement.Support;
using Microsoft.SharePoint.Taxonomy;
using MS.InformationManagement.Core.Documentset;
using Office = Microsoft.Office.DocumentManagement.DocumentSets;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint.Linq;

namespace MS.InformationManagement.BLL.SolicitudAnulacion
{
    public class SolicitudAnulacion
    {
        public static bool EnviarSolicitud(string IdRadicado, string Observaciones, Guid TargetLibrary)
        {
            bool result = false;
            try
            {
                Radicado CurrentRadicado = GetRadicado(TargetLibrary, IdRadicado);
                SPList targetList = SPContext.Current.Web.Lists.GetList(TargetLibrary, false);
                SPUser currentUser = SPContext.Current.Web.CurrentUser;

                if (CurrentRadicado.Id != null)
                {
                    int idDocumentSet = int.Parse(CurrentRadicado.Id.ToString());
                    Office.DocumentSet CurrentDocumentSet = GetDocumentSet(idDocumentSet, TargetLibrary);

                    SPContext.Current.Web.AllowUnsafeUpdates = true;
                    CurrentDocumentSet.Folder.Update();
                    CurrentDocumentSet.Folder.Item.Update();

                    CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_OBSERVACIONES] = Observaciones;
                    TaxonomyFieldValue TaxValue = TermStoreHelper.GetTaxonomyFieldByTerm(GlobalConstants.METADATA_GROUP_NAME, GlobalConstants.METADATA_TERM_STATUS, GlobalConstants.METADATA_TERM_STATUS_SOLICITUD_ANULAR);
                    CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS] = TaxValue;
                    CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_0] = TaxValue;

                    CurrentDocumentSet.Folder.Item.Update();
                    CurrentDocumentSet.Folder.Update();

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        SPUserToken systoken = SPContext.Current.Site.SystemAccount.UserToken;
                        using (SPSite currentSite = new SPSite(SPContext.Current.Web.Url, systoken))
                        {
                            using (SPWeb currentWeb = currentSite.OpenWeb())
                            {
                                currentWeb.AllowUnsafeUpdates = true;
                                SPList listAnulados = currentWeb.Lists.TryGetList(GlobalConstants.LIST_SOLICITUD_ANULADOS);
                                SPListItem newItem = listAnulados.Items.Add();
                                newItem[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_ID_RADICADO] = CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString();
                                newItem[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_ID_RADICADO_INTERNO] = CurrentDocumentSet.Folder.Item.ID.ToString();
                                newItem[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_LIST_TARGET] = targetList.Title;
                                newItem[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_OBSERVACIONES] = Observaciones;
                                newItem[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_DEPARTAMENTO] =  new MS.InformationManagement.BLL.GestionDeUsuarios.GestionDeUsuariosBLL().getProperty(GlobalConstants.UP_DEPARTMENT, currentUser.LoginName);;
                                newItem[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_ESTADO] = Estado.Pendiente.ToString();
                                newItem[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_USER] = currentUser;                                
                                newItem[SPBuiltInFieldId.Author] = currentUser;
                                newItem.Update();
                                currentWeb.AllowUnsafeUpdates = false;
                                result = true;

                            }
                        }
                    });
                }
                SPContext.Current.Web.AllowUnsafeUpdates = false;
                result = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return result;
        }

        public static Radicado GetRadicado(Guid libraryGuid, string documentID)
        {
            SPList targetList = SPContext.Current.Web.Lists.GetList(libraryGuid, false);
            using (DCDocumentCenterDataContext ctx = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                Radicado foundDocument = ctx.GetList<Radicado>(targetList.Title).SingleOrDefault(r => r.DocumentIDValue.Equals(documentID));
                if (foundDocument == null) return null;

                return foundDocument;
            }

        }

        
        public static Office.DocumentSet GetDocumentSet(int id, Guid TargetLibrary)
        {
            var spFolder = SPContext.Current.Web.Lists[TargetLibrary].GetItemById(id).Folder;
            return Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(spFolder);
        }

        public static string GetIdRadicado(int id, Guid TargetLibrary)
        {
            string result = string.Empty;
            var spFolder = SPContext.Current.Web.Lists[TargetLibrary].GetItemById(id).Folder;
            TaxonomyFieldValue Estado = (TaxonomyFieldValue)spFolder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS];
            if (Estado.Label != GlobalConstants.METADATA_TERM_STATUS_SOLICITUD_ANULAR && Estado.Label != GlobalConstants.METADATA_TERM_STATUS_ANULADO)
                result = spFolder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString();

            return result;
        }

        public static bool PuedoAnular(int id, Guid libraryGuid)
        {
            bool result = false;
            SPList currentList = SPContext.Current.Web.Lists[libraryGuid];
            if (currentList.BaseTemplate.ToString() != GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE)
                return false;

            var spFolder = currentList.GetItemById(id).Folder;
            if (spFolder == null) return false;
            string ContentType = spFolder.Item["ContentType"] + "";
            string DocumentosAdjuntos = spFolder.Item[CustomSiteColumns.FIELD_DOCUMENT_ATTACHEDDOCUMENTS] + "";
            TaxonomyFieldValue Estado = (TaxonomyFieldValue)spFolder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS];
            if (ContentType != GlobalConstants.CTTN_RADICADO_PERSONA && ContentType != GlobalConstants.CTTN_RADICADO_EMPRESA && string.IsNullOrEmpty(DocumentosAdjuntos))
                result = true;

            return result;
        }

    }
}
